package com.albaba.designpattern.flyweight.text_001;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 享元工厂 作用：创建和存储享元对象，当需要使用时直接返回，不需要重复创建。
 * @Author zx
 * @Date 2025/2/21 16:52
 * @Version 1.0
 */
public class FlyweightFactory {

    // 享元工厂
    private Map<String, Flyweight> pool = new HashMap<String, Flyweight>();

    // 实现享元对象之间的状态传递
    public FlyweightFactory() {
        // 添加对应的内部状态
        pool.put("A", new ConcreteFlyweight("A"));
        pool.put("B", new ConcreteFlyweight("B"));
        pool.put("C", new ConcreteFlyweight("C"));
        pool.put("D", new ConcreteFlyweight("D"));
    }

    // 根据内部状态返回对应的享元对象
    public Flyweight getFlyweight(String key) {
        if (pool.containsKey(key)) {
            System.out.println("具体享元" + key + "已经存在，被成功获取！");
            return pool.get(key);
        } else {
            System.out.println("具体享元" + key + "不存在，被创建！");
            ConcreteFlyweight flyweight = new ConcreteFlyweight(key);
            pool.put(key, flyweight);
            return flyweight;
        }
    }
}
